package mp

import (
	"context"
	"errors"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type ChapterSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewChapterSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChapterSaveLogic {
	return &ChapterSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ChapterSaveLogic) ChapterSave(req *types.ChapterReq) (resp string, err error) {
	course := &models.Course{Id: req.CourseId}
	has := db.GetData(course)
	if !has {
		return "", errors.New("课程不存在")
	}
	if course.Type == 20 {
		return "", errors.New("该课程不支持添加章节")
	}

	data := &models.Chapter{}
	copier.Copy(data, req)

	if req.Id == 0 {
		db.InsertData(data)
	} else {
		db.UpdateData(data, xb.Eq{"id": req.Id})
	}

	return "操作成功", nil
}
